from rest_framework import serializers
from user import models
import re

def chake_email(email):

    if not re.match(r"^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$",email):
        raise serializers.ValidationError("邮箱格式不正确")
    else:
        user=models.UserModel.objects.filter(email=email).first()
        if user:
            raise serializers.ValidationError("邮箱已存在")

def chake_phone(phone):
    if not re.match(r"^1[3-9]\d{9}$",phone):
        raise serializers.ValidationError("手机号格式不正确")
    else:
        home=models.UserModel.objects.filter(phone=phone).first()
        if home:
            raise serializers.ValidationError("手机号已存在")



def chake_username(name):
    name=models.UserModel.objects.filter(username=name).first()
    if name:
        raise serializers.ValidationError("用户名已存在")
class UserSer(serializers.ModelSerializer):
    class Meta:
        model=models.UserModel
        fields="__all__"

        extra_kwargs={
            "email":{
                "error_messages":{
                    "unique":"邮箱已存在",
                    "required":"邮箱不能为空"
                },
                "validators":[chake_email],

            },
            "phone":{
                "error_messages":{
                    "unique":"手机号已存在",
                    "required":"手机号不能为空"
                },
                "validators":[chake_phone],
            },
            "password":{
                "max_length":10,
                "min_length":6,
                "error_messages":{
                    "max_length":"密码长度不能超过10位",
                    "min_length":"密码长度不能少于6位",
                    "required":"密码不能为空"
                }
            },
            "username":{
                "error_messages":{
                    "required":"用户名不能为空",
                    "unique":'用户名已存在'
                },

                "validators":[chake_username],
            }
        }


